package com.yanfan.energy.service.impl;

import com.yanfan.attach.mapper.DeviceDetailMapper;
import com.yanfan.common.core.domain.AjaxResult;
import com.yanfan.common.utils.SecurityUtils;
import com.yanfan.energy.domain.EnergyPriceHistory;
import com.yanfan.energy.domain.EnergyPriceSetting;
import com.yanfan.energy.domain.statist.DateByStatistics;
import com.yanfan.energy.domain.statist.DateStatistics;
import com.yanfan.energy.domain.statist.PriceStatistics;
import com.yanfan.energy.mapper.*;
import com.yanfan.energy.service.EnergyPriceSettingService;
import com.yanfan.energy.util.WidgetUtil;
import com.yanfan.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 能源单价表(EnergyPriceSetting)表服务实现类
 *
 * @author makejava
 * @since 2022-09-28 11:07:00
 */
@Service("energyPriceSettingService")
@Transactional(rollbackFor = Exception.class)
public class EnergyPriceSettingServiceImpl implements EnergyPriceSettingService {
    @Resource
    private EnergyPriceSettingDao energyPriceSettingDao;
    @Resource
    private EnergyPriceHistoryDao energyPriceHistoryDao;
    @Resource
    private SysUserMapper sysUserDao;
    @Autowired
    private OverallEnergyDao overallEnergyDao;
    @Autowired
    private DeviceEnergyMapper deviceEnergyMapper;
    @Autowired
    private PurchasingEnergysDao purchasingEnergyDao;


    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public EnergyPriceSetting queryById(Integer id) {
        return this.energyPriceSettingDao.queryById(id);
    }

    /**
     * 分页查询
     *
     * @param energyPriceSetting 筛选条件
     * @param pageRequest        分页对象
     * @return 查询结果
     */
    @Override
    public Page<EnergyPriceSetting> queryByPage(EnergyPriceSetting energyPriceSetting, PageRequest pageRequest) {
        long total = this.energyPriceSettingDao.count(energyPriceSetting);
        return new PageImpl<>(this.energyPriceSettingDao.queryAllByLimit(energyPriceSetting, pageRequest), pageRequest, total);
    }

    /**
     * 新增数据
     *
     * @param energyPriceSetting 实例对象
     * @return 实例对象
     */
    @Override
    public EnergyPriceSetting insert(EnergyPriceSetting energyPriceSetting) {
        this.energyPriceSettingDao.insert(energyPriceSetting);
        return energyPriceSetting;
    }

    /**
     * 修改数据
     *
     * @param energyPriceSetting 实例对象
     * @return 实例对象
     */
    @Override
    public EnergyPriceSetting update(EnergyPriceSetting energyPriceSetting) {
        this.energyPriceSettingDao.update(energyPriceSetting);
        return this.queryById(energyPriceSetting.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.energyPriceSettingDao.deleteById(id) > 0;
    }

    @Override
    public List<EnergyPriceSetting> selectAllEnergyPriceSetting() {
        return energyPriceSettingDao.selectAllEnergyPriceSetting();
    }

    public List<EnergyPriceSetting> selectAllEnergyPriceSettingOld() {
        List<EnergyPriceSetting> energyPriceSettings = energyPriceSettingDao.selectAllEnergyPriceSetting();
        List<EnergyPriceSetting> energyPriceSettingByOne = new ArrayList<>();

        energyPriceSettings.stream().forEach(e -> {
            if (e.getType() == 8) {
                energyPriceSettingByOne.add(new EnergyPriceSetting(7, WidgetUtil.setPriceByDecimals(e.getPrice() * 1.25), 7, e.getCreatedBy(), e.getCreatedDate(), e.getLastModifiedDate(), e.getStartTime(), e.getEndTime()));
            }
        });
        energyPriceSettingByOne.stream().forEach(e -> {
            energyPriceSettings.add(e);
        });
        // 所有能耗
        List<DateStatistics> allEnergy = overallEnergyDao.findConsumeWaterByUnit("'%Y-%m-%d'", null, null, null, LocalDate
                .now()
                .plusDays(-LocalDate.now().getDayOfYear() + 1), LocalDate.now());
        // 查询所有单价(查找8为峰电、9为平电、10为谷电的单价)
        List<DateStatistics> price = energyPriceSettingDao.findPriceByType();


        // 6：蒸汽
        List<DateStatistics> vapour = allEnergy.stream().filter(d -> d.getCount() == 6L).collect(Collectors.toList());
        // 4：压缩空气
        List<DateStatistics> compress = allEnergy.stream().filter(d -> d.getCount() == 4L).collect(Collectors.toList());
        // 1：冷却水(空调热能)
        List<DateStatistics> air = allEnergy.stream().filter(d -> d.getCount() == 1L).collect(Collectors.toList());

        // 蒸汽
        // 天然气费 天然气费(一个月)÷蒸汽用量(一个月)=单价x蒸汽能耗m3
        // 天然气费用 natural
        List<DateStatistics> natural = purchasingEnergyDao.findNaturalByDate("'%Y-%m-%d'", LocalDate
                .now()
                .plusDays(-LocalDate.now().getDayOfYear() + 1), LocalDate.now());
        List<DateStatistics> TotalNatural = WidgetUtil.mergeByEnergyPrice(vapour);

        if (natural.isEmpty()) {
            natural.add(new DateStatistics(0L, "", 0.00));
        }

        if (TotalNatural.isEmpty() || TotalNatural.get(0).getNumber() == 0.00) {
            TotalNatural.add(new DateStatistics(0L, "", 1.00));
            TotalNatural.get(0).setNumber(1.00);
        }
        Double naturalPrice = natural.stream().findFirst().get().getNumber() / TotalNatural
                .stream()
                .findFirst()
                .get()
                .getNumber();
        energyPriceSettings.add(new EnergyPriceSetting(30, WidgetUtil.setPriceByDecimals(naturalPrice), 6, null, null, null, null, null));

        // 4：压缩空气
        // 总压缩空气设备电费/总压缩空气(流量计m3)=压缩空气单价x压缩空气能耗m3=压缩空气费用
        List<DateByStatistics> daoTotalByCompress = deviceEnergyMapper.findConsumeElectricity("'%Y-%m-%d'", null, null, null, 4, LocalDate
                .now()
                .plusDays(-LocalDate.now().getDayOfYear() + 1), LocalDate.now());
        List<DateByStatistics> dateByStatistics = WidgetUtil.computeByPrice(daoTotalByCompress, price);
        // 得到压缩空气总用电
        List<DateStatistics> compressByElectricity = WidgetUtil.mergeByElectricityPrice(dateByStatistics);
        // 得到压缩空气总能耗
        List<DateStatistics> cooling = WidgetUtil.mergeByEnergyPrice(compress);

        if (compressByElectricity.isEmpty()) {
            compressByElectricity.add(new DateStatistics(0L, "", 0.00));
        }
        if (cooling.isEmpty() || cooling.get(0).getNumber() == 0.00) {
            cooling.add(new DateStatistics(0L, "", 1.00));
            cooling.get(0).setNumber(1.00);
        }
        Double compressPrice = compressByElectricity.stream().findFirst().get().getNumber() / cooling
                .stream()
                .findFirst()
                .get()
                .getNumber();
        energyPriceSettings.add(new EnergyPriceSetting(31, WidgetUtil.setPriceByDecimals(compressPrice), 4, null, null, null, null, null));

        // 热能(冷却水)
        // 电费 -> 1：设备类型为空调热能(冷却水)的
        List<DateByStatistics> daoTotalByCooling = deviceEnergyMapper.findConsumeElectricity("'%Y-%m-%d'", null, null, null, 1, LocalDate
                .now()
                .plusDays(-LocalDate.now().getDayOfYear() + 1), LocalDate.now());
        // 把冷却水电价算出来
        List<DateByStatistics> dateByCooling = WidgetUtil.computeByPrice(daoTotalByCooling, price);
        // 得到冷却水总用电
        List<DateStatistics> coolingByElectricity = WidgetUtil.mergeByElectricityPrice(dateByCooling);
        // 得到冷却水总能耗
        List<DateStatistics> coolingCount = WidgetUtil.mergeByEnergyPrice(air);

        if (coolingByElectricity.isEmpty()) {
            coolingByElectricity.add(new DateStatistics(0L, "", 0.00));
        }
        if (coolingCount.isEmpty() || coolingCount.get(0).getNumber() == 0.00) {
            coolingCount.add(new DateStatistics(0L, "", 1.00));
            coolingCount.get(0).setNumber(1.00);
        }
        Double coolingPrice = coolingByElectricity.stream().findFirst().get().getNumber() / coolingCount
                .stream()
                .findFirst()
                .get()
                .getNumber();
        energyPriceSettings.add(new EnergyPriceSetting(32, WidgetUtil.setPriceByDecimals(coolingPrice), 11, null, null, null, null, null));

        return energyPriceSettings;
    }

    @Override
    public List<EnergyPriceSetting> selectAllEnergyPriceSettingJob() {
        List<EnergyPriceSetting> energyPriceSettings = energyPriceSettingDao.selectAllEnergyPriceSettingjob();
        return energyPriceSettings;
    }

    @Override
    @Transactional
    public AjaxResult updateEnergyPriceSetting(List<PriceStatistics> priceStatistics) {

        if (Objects.isNull(priceStatistics)) {
            return AjaxResult.error("入参为空");
        }
        if (!priceStatistics.isEmpty()) {
            priceStatistics.forEach(p -> {
                try {
                    // 查询历史设置
                    EnergyPriceSetting beginResult = energyPriceSettingDao.selectQueryById(p.getId());
                    EnergyPriceHistory energyPriceHistory = new EnergyPriceHistory();
                    energyPriceHistory.setType(p.getType());
                    energyPriceHistory.setPrice(p.getPrice());
                    // 设置对象
                    energyPriceHistory.setUnitTargetBefore(p.getType());
                    // 修改前单价
                    energyPriceHistory.setUnitPriceBefore(beginResult.getPrice());
                    // 修改后单价
                    energyPriceHistory.setUnitPriceAfter(p.getPrice());
                    // 创建时间
                    energyPriceHistory.setCreatedDate(new Date());
                    // 设置用户id
                    energyPriceHistory.setUserId(SecurityUtils.getUserId().intValue());
                    // 设置单价设置id
                    energyPriceHistory.setPriceSettingId(p.getId());
                    // 设置创建人
                    energyPriceHistory.setCreatedBy(SecurityUtils.getUsername());
                    if (Objects.nonNull(p.getBegin())) {
                        // 设置前时间
                        energyPriceHistory.setStartTime(new SimpleDateFormat("HH:mm:ss").parse(p.getBegin()));
                    }
                    if (Objects.nonNull(p.getEnd())) {
                        // 设置后时间
                        energyPriceHistory.setEndTime(new SimpleDateFormat("HH:mm:ss").parse(p.getEnd()));
                    }
                    // 修改能源单价消息
                    EnergyPriceSetting energyPriceSetting = new EnergyPriceSetting();
                    energyPriceSetting.setId(p.getId());
                    energyPriceSetting.setPrice(p.getPrice());
                    energyPriceSetting.setType(p.getType());
                    energyPriceSetting.setCreatedDate(new Date());
                    int endResult = energyPriceSettingDao.update(energyPriceSetting);

                    // 创建一条能源单价历史记录
                    energyPriceHistoryDao.insert(energyPriceHistory);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            });
        }


        return AjaxResult.success(this.energyPriceSettingDao.selectAllEnergyPriceSetting());
    }

    @Override
    public Map<String, List<EnergyPriceSetting>> findPriceElectric() {
        List<EnergyPriceSetting> energyPriceSettings = energyPriceSettingDao.findPriceElectric();
        Map<String, List<EnergyPriceSetting>> map = new LinkedHashMap<>();
        if (!energyPriceSettings.stream().filter(e -> e.getType() == 7).collect(Collectors.toList()).isEmpty()) {
            map.put("尖电", energyPriceSettings.stream().filter(e -> e.getType() == 7).collect(Collectors.toList()));
        }
        if (energyPriceSettings.stream().filter(e -> e.getType() == 7).collect(Collectors.toList()).isEmpty()) {
            List<EnergyPriceSetting> energyPriceSettings1 = new ArrayList<>();
            energyPriceSettings1.add(new EnergyPriceSetting(30, 0.00, 7, null, null, null, null, null));
            map.put("尖电", energyPriceSettings1);
        }

        if (!energyPriceSettings.stream().filter(e -> e.getType() == 8).collect(Collectors.toList()).isEmpty()) {
            map.put("峰电", energyPriceSettings.stream().filter(e -> e.getType() == 8).collect(Collectors.toList()));
        }
        if (energyPriceSettings.stream().filter(e -> e.getType() == 8).collect(Collectors.toList()).isEmpty()) {
            List<EnergyPriceSetting> energyPriceSettings1 = new ArrayList<>();
            energyPriceSettings1.add(new EnergyPriceSetting(31, 0.00, 8, null, null, null, null, null));
            map.put("峰电", energyPriceSettings1);
        }

        if (!energyPriceSettings.stream().filter(e -> e.getType() == 9).collect(Collectors.toList()).isEmpty()) {
            map.put("平电", energyPriceSettings.stream().filter(e -> e.getType() == 9).collect(Collectors.toList()));
        }
        if (energyPriceSettings.stream().filter(e -> e.getType() == 9).collect(Collectors.toList()).isEmpty()) {
            List<EnergyPriceSetting> energyPriceSettings1 = new ArrayList<>();
            energyPriceSettings1.add(new EnergyPriceSetting(32, 0.00, 9, null, null, null, null, null));
            map.put("平电", energyPriceSettings1);
        }

        if (!energyPriceSettings.stream().filter(e -> e.getType() == 10).collect(Collectors.toList()).isEmpty()) {
            map.put("谷电", energyPriceSettings.stream().filter(e -> e.getType() == 10).collect(Collectors.toList()));
        }
        if (energyPriceSettings.stream().filter(e -> e.getType() == 10).collect(Collectors.toList()).isEmpty()) {
            List<EnergyPriceSetting> energyPriceSettings1 = new ArrayList<>();
            energyPriceSettings1.add(new EnergyPriceSetting(33, 0.00, 10, null, null, null, null, null));
            map.put("谷电", energyPriceSettings1);
        }

        if (!energyPriceSettings.stream().filter(e -> e.getType() == 2).collect(Collectors.toList()).isEmpty()) {
            map.put("软化水", energyPriceSettings.stream().filter(e -> e.getType() == 2).collect(Collectors.toList()));
        }
        if (energyPriceSettings.stream().filter(e -> e.getType() == 2).collect(Collectors.toList()).isEmpty()) {
            List<EnergyPriceSetting> energyPriceSettings1 = new ArrayList<>();
            energyPriceSettings1.add(new EnergyPriceSetting(34, 0.00, 2, null, null, null, null, null));
            map.put("软化水", energyPriceSettings1);
        }

        return map;
    }

    @Override
    public List<EnergyPriceSetting> findAllPriceElectricSet() {
        List<EnergyPriceSetting> energyPriceSettings = energyPriceSettingDao.findPriceElectric();
        return energyPriceSettings
                .stream()
                .filter(e -> e.getType() == 7 || e.getType() == 8 || e.getType() == 9 || e.getType() == 10)
                .collect(Collectors.toList());
    }

    @Override
    public List<EnergyPriceSetting> findAll() {
        return energyPriceSettingDao.findALl();
    }
}
